<template>
  <view class="components-home">
    <view class="header">
      <image src='https://zhoukaiwen.com/img/wccQQP.png' mode='widthFix' class='header-image'></image>
    </view>
    <view class="content">
      <view class="current-posture">
        <view class="posture-image-container">
          <image :src="postureImage" mode="aspectFit" class="posture-image"></image>
        </view>
        <view class="posture-text">
          <text>当前姿势 ：{{ postureText }}</text>
        </view>
        <view class="record-time">
          <text>记录时长 ：{{ recordTime }}</text>
        </view>
      </view>
      <view class="button-container">
        <button v-if="timer" @click="stopListening">暂停记录</button>
        <button v-else @click="startListening">开始/继续记录</button>
        <button @click="saveData">保存数据</button>
      </view>
    </view>
  </view>
</template>


<script>
import { BluetoothUtil } from '../../common/BluetoothConnection.js';
import UniStorage from '../../common/UniStorage.js';
console.log(UniStorage);
const cache_name = 'myInfos';
export default {
  data() {
    return {
      currentPosture: '0',
      recordTime: '00:00',
			errorPosturePercent: 0.6,
      recordSecond: 0,
      totalErrorTime: 0,
      continueErrorTime: 0,
      errorStatus: false,
      checkTime: 20, // 设定多长时间算异常
      postureList: [
        { id: '0', name: '正常', imageUrl: '/static/posture_0.png' },
        { id: '1', name: '低头', imageUrl: '/static/posture_1.png' },
        { id: '2', name: '头部左偏', imageUrl: '/static/posture_2.png' },
        { id: '3', name: '头部右偏', imageUrl: '/static/posture_3.png' },
        { id: '4', name: '身体左斜', imageUrl: '/static/posture_4.png' },
        { id: '5', name: '身体右斜', imageUrl: '/static/posture_5.png' },
        { id: '6', name: '左手托腮', imageUrl: '/static/posture_6.png' },
        { id: '7', name: '右手托腮', imageUrl: '/static/posture_7.png' },
        { id: '8', name: '向前趴伏', imageUrl: '/static/posture_8.png' }
      ],
      wrongSittingPosture: new Set(['1', '2', '3', '4', '5', '6', '7', '8']),
      timer: null
    };
  },
  onHide() {
    BluetoothUtil.setCallback(null);
		if(this.recordSecond != 0) {
			this.saveData();
			console.log('保存结果了');
		}
  },
  computed: {
    postureText() {
      const posture = this.postureList.find(p => p.id === this.currentPosture);
      return posture ? posture.name : '未知坐姿';
    },
    postureImage() {
      const posture = this.postureList.find(p => p.id === this.currentPosture);
      return posture ? posture.imageUrl : '';
    }
  },
  methods: {
    saveData() {
			if(this.recordSecond == 0) {
				uni.showToast({
				  title: '您还未记录',
				  duration: 1500
				});
				return;
			}
      this.stopListening();
			const newInfo = {
				recordData:this.getFormattedCurrentTime(this.recordSecond),
				sittingTime : this.secondsToMinutesAndSeconds(this.recordSecond),
				errorPostureTime : this.secondsToMinutesAndSeconds(this.totalErrorTime),
				msg: (this.totalErrorTime / this.recordSecond) > this.errorPosturePercent ? '坐姿异常' : '坐姿正常' 
			}
			let sittingInfoArr = UniStorage.getItem(cache_name);
			sittingInfoArr.push(newInfo);
			UniStorage.clear();
			UniStorage.setItem(cache_name,sittingInfoArr);
      this.recordSecond = 0;
			this.totalErrorTime = 0;
      this.recordTime = '00:00';
			uni.showToast({
			  title: '保存成功',
			  duration: 1500
			});
    },
    startListening() {
      console.log('开始/继续检测');
      this.startTimer();
      在这里添加开始监听的逻辑
      BluetoothUtil.setCallback((resHex, str) => {
        console.log('调用方resHex', resHex);
        console.log('调用方str:', str);
        if (resHex[1] == '0' || str[1] == '0') {
          console.log('正常');
          this.continueErrorTime = 0;
          this.errorStatus = false;
        } else {
          console.log('异常');
          this.errorStatus = true;
        }
        if (resHex.length <= 3) {
          this.updatePosture(resHex[1]);
        } else {
          this.updatePosture(str[1]);
        }
      })
      BluetoothUtil.handleValue()
    },
    stopListening() {
      console.log('暂停监听');
      clearInterval(this.timer); // 清除定时器
      this.timer = null; // 将定时器ID置为空
      // 在这里添加暂停监听的逻辑
      BluetoothUtil.setCallback(null);
      this.continueErrorTime = 0;
      this.errorStatus = false;
    },
    getFormattedCurrentTime() {
      var now = new Date();
      var year = now.getFullYear();
      var month = now.getMonth() + 1; // JavaScript中的月份从0开始，所以需要+1
      var day = now.getDate();
      var hour = now.getHours();
      var minute = now.getMinutes();

      // 补零操作，确保单个数字的日期和时间前有0
      month = month < 10 ? '0' + month : month;
      day = day < 10 ? '0' + day : day;
      hour = hour < 10 ? '0' + hour : hour;
      minute = minute < 10 ? '0' + minute : minute;

      // 根据题目要求，只需月份、日期和小时:分钟
      var formattedTime = month + '月' + day + '日' + hour + ':' + minute;

      return formattedTime;
    },
    handler(res) {
      console.log(res);
    },
    startTimer() {
      if (this.timer) {
        clearInterval(this.timer); // 确保没有重复的定时器在运行
      }
      this.timer = setInterval(() => {
        this.recordSecond++;
        this.recordTime = this.secondsToMinutesAndSeconds(this.recordSecond);
        console.log('当前坐姿状态', this.errorStatus);
        console.log('当前异常时间', this.continueErrorTime);
        if (this.errorStatus) {
          this.continueErrorTime++;
        }
        if (this.continueErrorTime >= this.checkTime) {
          this.totalErrorTime++;
        }
      }, 1000);
    },
    secondsToMinutesAndSeconds(seconds) {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      const formattedMinutes = String(minutes).padStart(2, '0');
      const formattedSeconds = String(remainingSeconds).padStart(2, '0');
      return `${formattedMinutes}:${formattedSeconds}`;
    },
    updatePosture(postureId) {
      this.currentPosture = postureId;
      console.log('当前姿势为', postureId)
      if (this.wrongSittingPosture.has(postureId)) {
        if (this.errorStatus && this.continueErrorTime > this.checkTime) {
          console.log('应该振动了...')
          uni.vibrateLong({
            success: function () {
              console.log('success');
            }
          });
        }
      }
    },
  },
  mounted() {
    // 模拟坐姿变化，可以替换成实际的坐姿检测逻辑
    // setInterval(() => {
    //   const newPosture = Math.floor(Math.random() * 9);
    //   this.updatePosture(newPosture);
    // }, 1500);
  }
};
</script>

<style scoped>
.components-home {
  background-color: #e0f7fa;
  /* 背景颜色，柔和的蓝色 */
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
  height: 100vh;
  /* 高度设为100vh，使其占满整个视口 */
}

.header {
  width: 100%;
  height: 486rpx;
  position: relative;
  background-color: #b2ebf2;
  /* 背景颜色，比外层略深 */
  border-radius: 20rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 20rpx;
  /* 添加间距分开顶部图片和下方展示区 */
}

.header-image {
  width: 100%;
  height: 100%;
  border-radius: 20rpx;
  display: block;
  /* 确保图片为块级元素 */
}

.content {
  width: 100%;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.current-posture {
  width: 90%;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #ffffff;
  /* 白色背景 */
  padding: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 20rpx;
  /* 添加间距分开内容区和按钮 */
}

.posture-image-container {
  margin-top: 40rpx;
  width: 220rpx;
  height: 220rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.posture-image {
  width: 100%;
  height: 100%;
  border-radius: 20rpx;
}

.posture-text,
.record-time {
  margin-top: 40rpx;
  font-size: 30rpx;
  color: #333;
  background-color: #e0f2f1;
  /* 柔和的绿色背景 */
  padding: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}

.text {
  color: #555;
  font-size: 24rpx;
}

.button-container {
  margin-top: 20rpx;
  width: 100%;
  display: flex;
  justify-content: space-around;
  padding: 10rpx;
  background-color: #e0f2f1;
}

button {
  padding: 20rpx 40rpx;
  font-size: 30rpx;
  border: none;
  border-radius: 20rpx;
  background-color: #ecffcf;
  color: #000000;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}

button:active {
  background-color: #aabaca;
}
</style>